*** This do file creates the balance table but by view
*local with the balance variables
#delimit ;
local balance_vars = " depfp age ado bmi 
	single cohabiting married 
	tertiary secondary primary no_educ
	salaried self_employed student domestic
	pregnancies children delivery_ever    
	spacing_nomore spacing_less3yrs spacing_more3yrs 
	current_larc current_sarc current_nonmc " ;
#delimit cr
*get the stats for joint orthogonality
use "${PilotPublicData}/hgopy_pilot_public.dta", clear 
*remove not randomized 
drop if view==0 
*first group
reg view `balance_vars' 
testparm `balance_vars'
local fstat = r(F)
local fstat_f : display %9.2f `fstat'
local pval =  r(p)
local pval_f : display %9.2f `pval'
di "`fstat" "`pval"
*load dataset
use "${PilotPublicData}/hgopy_pilot_public.dta", clear
drop if view==0
count
numlabel, remove
*get list of binary vars
su `balance_vars'
local binary = "" 
local continuous = ""
qui foreach v of varlist `balance_vars' {
	su `v' , 
	if (`r(min)'==0 & `r(max)'==1) {
		local binary = "`binary' `v'"
	}
	else if !(`r(min)'==0 & `r(max)'==1) {
		local continuous = "`continuous' `v'"
	}
}
*load local with variable labels
qui foreach v of local balance_vars {
	local varlab_`v' : variable label `v'
}
*create the table
iebaltab `balance_vars' , grpvar(view) control(1) order(1 2) browse rowvarlabels tblnonote format(%9.2f) onerow pt std starsnoadd
*clean up 
egen x = fill( 0 1 0 1)
replace x=. if _n<=3
foreach v of varlist v2 v3 {
	gen x`v' = `v'[_n+1] if x==1
	order x`v', after(`v')
}
drop if v1=="" & !missing(x)
drop x 
*Fix labels
replace v2 = "IDM" if _n == 2
replace v3 = "SDM" if _n == 2

*add joint-ortho test
local n = _N +2
set obs `n'
local n = _N-1
replace v4 = "`fstat_f'" in `n'
replace v1 = "Test of joint orthogonality, F-stat" in `n'
local n = _N
replace v4 = "`pval_f'" in `n'
replace v1 = "p-value" in `n'
*reorder
gen n=_n
replace n = 50 if v1=="N"
sort n
drop n 
*clean up parentheses
qui foreach v of varlist xv2 xv3  {
	replace `v'=subinstr(`v',"[","(",.)
	replace `v'=subinstr(`v',"]",")",.)	
}
*remove parentheses for dummies
qui foreach v of local binary {
	replace xv2="" if v1=="`varlab_`v''"
	replace xv3="" if v1=="`varlab_`v''"
}
qui foreach v of local continuous {
	replace v2=v2+"/"+xv2 if v1=="`varlab_`v''"
	replace v3=v3+"/"+xv3 if v1=="`varlab_`v''"
}
drop xv*
*remove first few rows
drop if _n<4
*save
#delimit ;
texsave_custom using "${OutTexTab}/TabS4-balance-view.tex" , replace nonames  hlines(24 26) frag
	align(lccc)
	headerlines("& (1) & (2) & (3) "
				" & \textbf{IDM} & \textbf{SDM} & "
				" & Mean/(SD) & Mean/(SD) & Diff. (p-value) ")	;
#delimit cr

